﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Twodi.Aspect.Interfaces;
using Microsoft.Xna.Framework;
using System.ComponentModel;
using Twodi.Structs;

namespace Twodi.Implemented
{
    public class AbstractMappedContainer<T> : AbstractContainer<T> where T : IBoundsAspect
    {
        public AbstractMappedContainer(Game game)
            : base(game)
        {
            this.Components.ListChanged += (sender, e) =>
            {
                if (e.ListChangedType == ListChangedType.Reset)
                {
                    Mapping.Clear();
                }
            };
        }

        public AbstractMappedContainer(int capacity, Rectangle bounds, Game game)
            : this(game)
        {
            CreateMapping(capacity, bounds);
        }

        public void CreateMapping(int capacity, int maxLevel, Rectangle bounds)
        {
            Mapping = new Quadtree<T>(capacity, maxLevel, bounds);
            CreateMapping();
        }

        public void CreateMapping(int capacity, Rectangle bounds)
        {
            Mapping = new Quadtree<T>(capacity, bounds);
            CreateMapping();
        }

        private void CreateMapping()
        {
            Components.ListChanged += (sender, e) =>
            {
                if (e.NewIndex < 0) return;

                Mapping.Add(Components[e.NewIndex]);
                Components[e.NewIndex].PositionProperties.PositionChanged += (sender2, e2) =>
                {
                    Mapping.Moved(Components[e.NewIndex], e2.PreviousPosition);
                };
            };

            for (int i = 0; i < Components.Count; i++)
            {
                Components[i].PositionProperties.PositionChanged += (sender, e) =>
                {
                    Mapping.Moved(Components[i], e.PreviousPosition);
                };
            }
        }

        public Quadtree<T> Mapping
        {
            get;
            protected set;
        }
    }
}
